package cn.edu.dlut.ssdut.foodCredit2012.service;

import java.util.List;

import org.hibernate.Query;
import org.hibernate.Session;

import cn.edu.dlut.ssdut.foodCredit2012.model.Admin;
import cn.edu.dlut.ssdut.foodCredit2012.util.HibernateUtil;

public class AdminService {
	
	Admin a = new Admin();
	
	public void add(Admin a)throws Exception{
		if(!isAdmin(a)) {
			Session session = HibernateUtil.getUserSessionFactory().getCurrentSession();
			session.beginTransaction();
			session.save(a);
			session.getTransaction().commit();
		}
	}
	
	
	
	public Admin load(Admin a) throws Exception {
		if(isAdmin(a)){
			a = loadByID(a.getId());
			return a;
		}
		return a;
	}
	
	public Admin loadByID(int id) throws Exception{
		
		Session session = HibernateUtil.getUserSessionFactory().getCurrentSession();
		session.beginTransaction();
		
		a=(Admin)session.get(Admin.class, id);
		
			
		session.getTransaction().commit();
		
		return a;
	}
	
	
	
	public void update (Admin a) throws Exception{
		if(isAdmin(a)){
			Session session = HibernateUtil.getUserSessionFactory().getCurrentSession();
			session.beginTransaction();
			session.update(a);
			session.getTransaction().commit();
		}
	}
	
	public void delete(Admin a) throws Exception{
		if(isAdmin(a)) {
			Session session = HibernateUtil.getUserSessionFactory().getCurrentSession();
			session.beginTransaction();
			session.delete(a);
			session.getTransaction().commit();
		}
	}
	
	
	
	public List<Admin> userList() {
		List<Admin> adminList = null;
		Session session = HibernateUtil.getUserSessionFactory().getCurrentSession();
		session.beginTransaction();
		
		Query query = session.createQuery("from Admin");
		query.setFirstResult(2);
		query.setMaxResults(10);
		adminList = (List<Admin>)query.list();
		
		session.getTransaction().commit();
		
		return adminList;
	}
	
	public boolean isAdmin(Admin u) throws Exception {
		Session session = HibernateUtil.getUserSessionFactory().getCurrentSession();
		session.beginTransaction();
		long count = (Long)session.createQuery("select count(*) from Admin a where a.id = :id")
			.setInteger("id", a.getId())
			.uniqueResult();
		
		session.getTransaction().commit();
		
		if(count > 0) return true;
		return false;
		
	}
	
	public boolean login(Admin a) throws Exception {
		Session session = HibernateUtil.getUserSessionFactory().getCurrentSession();
		session.beginTransaction();
		long count = (Long)session.createQuery("select count(*) from Admin a where a.name = :name and a.passWord = :password")
			.setString("name", a.getName())
			.setString("password", a.getPassWord())
			.uniqueResult();
		
		session.getTransaction().commit();
		
		if(count > 0) return true;
		return false;
		
	}
	
	
	

}
